package cn.edu.zzuli.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.JWTVerifier;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class JwtUtil {
    private static final String TOKEN_SECRET="ekij**wall**from**zzuli??";  //密钥盐,为了加盐，内容随意

    public static final long EXPIRE_TIME= 24 * 3600 * 1000;//token到期时间24小时，毫秒为单位
//    public static final long EXPIRE_TIME= 60 * 1000;//token到期时间24小时，毫秒为单位
    /**
     * 生成token
     * @param id
     * @param username
     * @return 返回一个token
     * @expireTime
     */
    public static String sign(String id, String username, Long expireTime){
        // 签发时间
        Date iatDate = new Date();

        Date expireAt=new Date(expireTime+EXPIRE_TIME);

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");
        String token = null;
        try {
            token = JWT.create()
                    .withIssuer("ekijOfZzuli")
                    .withClaim("username", username)
                    .withClaim("uid", id)
                    .withExpiresAt(expireAt)  // 设置过期的日期
                    .withIssuedAt(iatDate)        // 签发时间
                    .sign(Algorithm.HMAC256(TOKEN_SECRET));

        } catch (IllegalArgumentException | JWTCreationException je) {
            log.info("不会吧，不会吧，加密出错了");
        }

        return token;

    }

    /**
     * 解密
     * @param token
     * @return
     * @throws Exception
     */
    public static boolean verifyToken(String token) {
        JWTVerifier verifier = null;
        try {
            verifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).withIssuer("ekijOfZzuli").build();
            DecodedJWT jwt = verifier.verify(token);  // 核实token
            return true;
        } catch (com.auth0.jwt.exceptions.TokenExpiredException e) {
            log.info("token 过期了, " + e.getMessage());
            return false;
        } catch (Exception e) {
            log.error("解密错误?");
            return false;
        }
    }

    public static String getIdOfToken(String token){
        try{
            DecodedJWT decodedJWT = JWT.decode(token);
            System.out.println(decodedJWT.getClaim("account").getClass());
            return decodedJWT.getClaim("uid").asString();

        }catch (JWTCreationException ce){
            log.error("token 创建异常" + ce.getMessage());
            return null;
        }catch (JWTDecodeException de) {
            log.error("token 解析异常" + de.getMessage());
            return null;
        }
    }


}
